package com.youxin.cpcenter.common.cors;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import com.youxin.busfoundation.common.BuildConfig;
import com.youxin.busfoundation.common.GlobalConfig;
import com.youxin.foundation.utils.StringUtils;

@Configuration
public class CORSFilter extends CorsFilter {

	public CORSFilter(CorsConfigurationSource source) {
		super((CorsConfigurationSource) source);
	}

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		if (StringUtils.contains(response.getHeader("Access-Control-Allow-Headers"), GlobalConfig.TOKEN_NAME,false) == false) {
			response.addHeader("Access-Control-Allow-Headers",
					"Access-Control-Allow-Origin, Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Cache-Control, Access-Control-Request-Headers, "+GlobalConfig.TOKEN_NAME);
		}
		if (StringUtils.isNullOrEmpty(response.getHeader("Access-Control-Allow-Origin"))) {
			response.addHeader("Access-Control-Allow-Origin", "*");

//			if (BuildConfig.isProduction()) {
//				response.addHeader("Access-Control-Allow-Origin", ",http://qiye.slsai.com,https://qiye.slsai.com");
//			} else {
//				response.addHeader("Access-Control-Allow-Origin", "*");
//			}
		}
		filterChain.doFilter(request, response);
	}

}